<template>
  <div id="chartTop" ref="EcharRef" class="monitorContainer"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, watch, nextTick } from 'vue';

const EcharRef = ref(null);

// 获取父组件数据
const props = defineProps({
  chartOption: {
    type: Object,
    default: () => ({}),
  },
});

let myChart = null;

onMounted(() => {
  initChart();
});

watch(
  () => props.chartOption,
  (newVal) => {
    if (myChart && newVal.seriesData && newVal.seriesData.length > 0) {
      setOption(newVal);
    }
  },
  { deep: true }
);

const initChart = () => {
  nextTick(() => {
    const chartDom = document.getElementById('chartTop');
    if (chartDom) {
      myChart = echarts.init(chartDom);
      setOption(props.chartOption);
    }
  });
};

const setOption = (option) => {
  if (myChart) {
    myChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{b}<br />总占比：{d}%',
        backgroundColor: '#FFFFFF',
        borderColor: '#eef3f8',
        borderWidth: 1,
        textStyle: {
          color: '#8C8C8C',
        },
        padding: 12,
      },
      label: {
        formatter: ['{name|{b}}', '{percentage|{d}%}'].join('\n'),
        rich: {
          name: {
            color: '#333333',
            fontWeight: 'bolder',
            align: 'left',
          },
          percentage: {
            color: '#000000',
            lineHeight: 15,
            align: 'left',
          },
        },
      },
      labelLine: {
        lineStyle: {
          color: '#BFBFBF',
        },
      },
      series: [
        {
          type: 'pie',
          roseType: 'radius',
          radius: [33, 100],
          center: ['50%', '50%'],
          data: option.seriesData,
          animationEasing: 'cubicInOut',
          animationDuration: 2600,
        },
      ],
      color: ['#85A7FF', '#99EBBD', '#FFB18B', '#C6EBFF', '#BECCE6'],
    });
  }
};
</script>

<style scoped>
.monitorContainer {
  width: 100%;
  height: 300px;
}
</style>